package services;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Member;

import core.Lookup;
import core.MemberManagerLocal;

import utils.Utils;
import utils.WebUtils;

public class Login extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		
		process(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		process(req,resp);
	}

	private void process(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
		String memberCellphone = WebUtils.safeGetParameterString(req, "memberCellphone");
		String memberEmail = WebUtils.safeGetParameterString(req, "memberEmail");
		String memberPassword = WebUtils.safeGetParameterString(req, "memberPassword");
		
		String outputString;
		
		if(Utils.isEmpty(memberEmail) || Utils.isEmpty(memberEmail)){
			resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "email or cellphone are required");
			return;
		}		
		
		if(Utils.isEmpty(memberPassword)){
			resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "password parameter is required");
			return;
		}
		
		MemberManagerLocal memberManager = Lookup.lookupMemberManager();
		
		Member member = memberManager.loginMember(memberCellphone, memberEmail, memberPassword);
		
		if(member == null){
			resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid Member");
			return;
		}else{
			outputString = "{success: true}";	
		}
		
		PrintWriter writer = resp.getWriter();
		resp.setContentType("text/html;charset=UTF-8");
		writer.print(outputString);
		writer.close();		
		
	}
}
